package com.itheima.controller;

import com.itheima.domain.Result;
import com.itheima.utils.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@RestController
@Slf4j
public class UploadController {

//    private static final String UPLOAD_DIR = "D:\\image\\";

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    /**
     * 本地文件上传
     * @param username
     * @param age
     * @param file
     * @return
     */
   /* @PostMapping("/upload")
    public Result upload(String username, Integer age, MultipartFile file) {
        log.info("上传参数:username={},age={},file={}", username, age, file);
        //1. 修改文件名
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //生成一个新的名字 uuid + 原始文件的后缀
        String newFileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //2. 初始化上传文件夹
        //判断文件夹是否存在,如果不存在,创建文件夹
        File dir = new File(UPLOAD_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        //3.转存
        try {
            //将文件转存到D:\\image文件夹下
            file.transferTo(new File(UPLOAD_DIR + newFileName));//转存文件
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success();
    }*/

    /**
     * 文件上传-阿里云OSS
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        try {
            String url = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
            return Result.success(url);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("上传失败");
        }
    }

}
